package com.jinly.ryder.ssh.command;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.ssh.command.model.OsInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class OsCommand {
    private Session sshSession;

    public OsCommand(Session sshSession) {
        this.sshSession = sshSession;
    }

    public OsInfo exec() {
        ChannelExec channelExec = null;
        BufferedReader reader = null;
        String command = "cat /etc/os-release";
        OsInfo osInfo = null;
        try {
            channelExec = (ChannelExec) sshSession.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.connect();
            reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String line;
            Map<String, String> map = new HashMap<>();
            while ((line = reader.readLine()) != null) {
                String[] ss = line.replaceAll("\"", "").split("=");
                if (ss.length == 2) {
                    map.put(ss[0].trim(), ss[1].trim());
                }
            }
            osInfo = new OsInfo();
            osInfo.setOsName(map.get("ID"));
            osInfo.setOsVersion(map.get("VERSION_ID"));
        } catch (Exception e) {
            log.error("ssh {}  err:{}", command, e.getMessage());
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError("ssh命令执行失败");
        } finally {
            try {
                if (reader != null) reader.close();
                if (channelExec != null) channelExec.disconnect();
            } catch (Exception e) {
            }
        }
        return osInfo;
    }

}

